﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using DevExpress.Data.Filtering;
using POI.eTransmittal.Enitity;
using POI.eTransmittal.BusinessRule;
using System.IO;
using DevExpress.Utils;

namespace POI.eTransmittal.WebApp
{
    public partial class InquiryOutgoing : BasePage 
    {
        const string KEY_EMPLOYEE_CRITERIA = "POI.eTransmittal.Outgoing.EmpCriteria";
        protected void Page_Init(object sender, EventArgs e)
        {
            RegisterXpodatasource(xpoDsContact, xpodsTransmittal,xpodsDocType,xpodsUser );
            if (!IsPostBack)
                Session.Remove(KEY_EMPLOYEE_CRITERIA);
            //if (Session[KEY_EMPLOYEE_CRITERIA] != null)
            //{
            //    xpodsTransmittal.Criteria = Session[KEY_EMPLOYEE_CRITERIA].ToString();
            //}
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected override void SetErrorMessage(string message)
        {
            if (!hfEdit .Contains("error"))
                hfEdit.Add("error", message);
            else
                hfEdit["error"] = message;
        }
        protected override void SetFlashMessage(string message)
        {
            if (!hfEdit.Contains("info"))
                hfEdit.Add("info", message);
            else
                hfEdit["info"] = message;
        }
        protected void grdTransmittal_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            grdTransmittal.DataBind();
        }

      
        protected void upcDocument_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
        {
            if (e.UploadedFile != null)
            {
               // TempFile.StoreTempFile(this, e.UploadedFile);
                TempFile.StoreToTempFolder(this, e.UploadedFile);
                e.CallbackData = Path.GetFileName(e.UploadedFile.FileName);
                e.IsValid = true;
            }
        }

        protected void clbpnlPopEdit_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            string prm = e.Parameter;
            int opType = 0;
            int idValue = 1;
            string[] pars = e.Parameter.Split(';');
            switch (pars[opType])
            {
                case "load":
                    loadEdit(pars[idValue]);
                    break;
                case "save":
                    saveEdit(pars[idValue],false);
                    break;
                case "send":
                    sendTransmittal(pars[idValue]);
                    break;
                case "submit":
                    submitTransmittal(pars[idValue]);
                    break;
            }
        }

        private void submitTransmittal(string p)
        {
            OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, p);
            if (trns != null)
            {
                if (string.IsNullOrEmpty(trns.FaxFileLink)&& TempFile.GetFileFromSession(this)==null )
                    SetErrorMessage("Error: please upload the document first");
                else
                {
                        saveEdit(p, false);
                        trns.Reload();
                        trns.Status = OutgoingTransmittal.WAIT;
                        trns.Save();
                        CurrentUnitOfWork.CommitChanges();
                        CommonBusinessRules.SubmitToCoordinator(trns, "http://" + HttpContext.Current.Request.Url.Host + "/"+HttpContext.Current.Request.ApplicationPath);
                        if (!hfEdit.Contains("error"))
                        {
                            SetFlashMessage("Your transmittal is successfully submitted.");
                        }

                }
            }
        }

        private void sendTransmittal(string id)
        {
            saveEdit(id, true);
        }

        private void saveEdit(string id,bool sendFax)
        {
            string subject = txtEditSubject.Text;
            string faxNo = txtEditFaxNo.Text;
            string author = cboAuthor.Text;
            string to = cboEditTo.Text;
            string remarks = txtEditRemarks.Text;
            string docTypeCode = cboEditDocType.Value == null ? "" : cboEditDocType.Value.ToString();
            string attn = txtEditAttn.Text;
           string log=id;
      
         TempFile file=   TempFile.GetFileFromSession(this);
         string shareFolder;
         int step = 0;
         bool isErr = false;
            try
            {
                if (file == null)
                {
                    step = 1;
                    CommonBusinessRules.SaveOutgoing(CurrentUnitOfWork,log, subject, author, to, faxNo, docTypeCode, attn,remarks, CurrUserId);
                
                }
                else
                {
                    string ext = Path.GetExtension(file.File.FileName);

                    CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);

                    string path = CommonBusinessRules.GetOutgoingShareFolderToWrite(CurrentUnitOfWork,log);
                 //   step = 2;
                    string newFileName = CommonBusinessRules.GetOutgoingTransmittalFileName(CurrentUnitOfWork, log, Path.GetExtension(file.File.FileName));
                    shareFolder = Path.Combine(path, newFileName);
                    file.File.SaveAs(shareFolder);
                    step = 1;
                    CommonBusinessRules.SaveOutgoing(CurrentUnitOfWork, log, subject, author, to, faxNo, docTypeCode, attn, remarks, CurrUserId, file.File.FileName , shareFolder);
                }
                if (sendFax)
                {
                    step = 3;
                    CommonBusinessRules.SendFax(CurrentUnitOfWork, log);
                }
            }
            catch (Exception ex)
            {
                isErr = true;
                switch (step)
                {
                    case 0:
                        SetErrorMessage("Error:Unable to write document;" + ex.Message);
                        break;
                    case 1:
                        SetErrorMessage("Error:unable to save transmittal;" + ex.Message);
                        break;
                    case 3:
                        SetErrorMessage(ex.Message);
                        break;
                    default:
                        SetErrorMessage("Error:" + ex.Message);
                        break;
                }
            }
            if (!isErr)
            {
                string op = sendFax ? "sent" : "saved";
                SetFlashMessage("Your Transmittal is " + op + " successfully, with the following information:<br/>Transmittal Log Number : " + id.ToString());
            }
            TempFile.Clear(this);
        }

        private void loadEdit(string id)
        {
            OutgoingTransmittal trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, id);
            if (trns != null)
            {
                if (CurrentUserRole != null)
                {
                    if (!CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_OUTGOING_TRANSMITTAL ))
                    {
                        btnSendFax .ClientEnabled = false;
                        btnSave.ClientEnabled = false;
                        btnSubmit.ClientEnabled = false;
                    }
                    else
                    {
                        btnSendFax.ClientEnabled = true;
                        btnSave.ClientEnabled = true;
                        btnSubmit.ClientEnabled = true;
                    }
                }
                //lblStatus.Text = trns.Status;
                lblLog.Text = String.Format("{0} ({1})", trns.ID.ToString(), trns.Status); ;
                lblRefNo.Text = trns.RefNo;
                txtEditAttn.Text = trns.Attn;
                txtEditFaxNo.Text = trns.FaxNo;
                txtEditRemarks.Text = trns.Remarks;
                txtEditSubject.Text = trns.Subject;
                cboEditDocType.Value = trns.DocTypeCode;
                cboAuthor.Text = trns.Author;
                cboEditTo.Text = trns.To;
                btnChange.Text = trns.OriginalFileName;
             
                if (!hfEdit.Contains("uncLink"))
                    hfEdit.Add("uncLink", trns.UNC_LINK);
                else
                    hfEdit["uncLink"] = trns.UNC_LINK;

                btnSendFax.Enabled = (trns.Status == OutgoingTransmittal.WAIT);
                btnSubmit.Enabled = (trns.Status == OutgoingTransmittal.DRAFT);
               
                TempFile.Clear(this);
            }
        }

        protected void grdTransmittal_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {

        }

        protected void clbCancel_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            OutgoingTransmittal trns=CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork,e.Parameter);
            if (trns != null)
            {
                TempFile.Clear(this);
                e.Result = trns.OriginalFileName;
            }
        }

        protected void hfEdit_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            string[] prms = e.Parameter.Split(';');
            string value = "";
            if (prms.Length == 1)
            {
                TempFile tf = TempFile.GetFileFromSession(this);
                if (!string.IsNullOrEmpty(tf.TempFileLoc))
                {
                    value = tf.TempFile_UNC_Link;
                }
            }
            else
            {
                OutgoingTransmittal  trns = CommonBusinessRules.GetOutgoingTransmittal(CurrentUnitOfWork, prms[1]);
                if (trns != null)
                {
                    value = trns.GetUNC_FileLink();
                }
            }

            if (!hfEdit.Contains("uncLink"))
                hfEdit.Add("uncLink", value);
            else
                hfEdit["uncLink"] = value;
        }

        protected void grdTransmittal_CommandButtonInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCommandButtonEventArgs e)
        {
            if (CurrentUserRole != null)
            {
                //  if (e.ButtonType != DevExpress.Web.ASPxGridView.ColumnCommandButtonType.Delete) return;
                string createdBy = (string)grdTransmittal.GetRowValues(e.VisibleIndex, "CreatedBy");
                //    OutgoingTransmittal trn = (OutgoingTransmittal)grdTransmittal.GetRow(e.VisibleIndex);
                if (CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_OUTGOING_TRANSMITTAL)) return;
                e.Visible = createdBy == CurrUserId;

            }
        }

        protected void grdTransmittal_CustomButtonInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonEventArgs e)
        {
            //if (CurrentUserRole != null)
            //{
               
            //    if (e.ButtonID == "custEdit")
            //    {
            //        if (CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_OUTGOING_TRANSMITTAL)) return;
            //  string createdBy=(string)    grdTransmittal.GetRowValues(e.VisibleIndex, "CreatedBy");
            //        //OutgoingTransmittal trn = (OutgoingTransmittal)grdTransmittal.GetRow(e.VisibleIndex);
            //  if (createdBy == CurrUserId)
            //  {
            //      e.Visible = DefaultBoolean.True;
            //  }
            //  else
            //      e.Visible = DefaultBoolean.False;
            //      //  e.Enabled = createdBy == CurrUserId? DevExpress.Web.ASPxClasses.DefaultBoolean.True:
            //    }
            //}
        }
    }
}